<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
  <head>
    <th:block th:insert="~{include :: header('新增设备指令')}" />
  </head>
  <body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight">
      <div class="ibox float-e-margins">
        <div class="ibox-title">
          <h5>新增设备指令 <small>请填写指令相关信息</small></h5>
          <div class="ibox-tools">
            <a class="collapse-link">
              <i class="fa fa-chevron-up"></i>
            </a>
          </div>
        </div>
        <div class="ibox-content">
          <form class="form-horizontal m" id="form-command-add">
            <div class="form-group">
              <label class="col-sm-3 control-label"
                >设备选择 <span class="text-danger">*</span>：</label
              >
              <div class="col-sm-8">
                <div class="input-group">
                  <span class="input-group-addon"
                    ><i class="fa fa-microchip"></i
                  ></span>
                  <select
                    class="form-control selectpicker"
                    name="deviceId"
                    id="deviceId"
                    data-live-search="true"
                    required
                  >
                    <option value="">请选择设备</option>
                    <!-- 设备列表将通过JavaScript动态加载 -->
                  </select>
                </div>
              </div>
            </div>
            <div class="form-group">
              <label class="col-sm-3 control-label"
                >指令类型 <span class="text-danger">*</span>：</label
              >
              <div class="col-sm-8">
                <div class="input-group">
                  <span class="input-group-addon"
                    ><i class="fa fa-code"></i
                  ></span>
                  <input
                    type="text"
                    class="form-control"
                    name="commandType"
                    id="commandType"
                    placeholder="请输入指令类型"
                    required
                  />
                </div>
                <span class="help-block m-b-none"
                  ><i class="fa fa-info-circle"></i>
                  对于配置更新，请输入CONFIG_UPDATE</span
                >
              </div>
            </div>
            <div class="form-group">
              <label class="col-sm-3 control-label"
                >过期时间 <span class="text-danger">*</span>：</label
              >
              <div class="col-sm-8">
                <div class="input-group">
                  <span class="input-group-addon"
                    ><i class="fa fa-clock-o"></i
                  ></span>
                  <input
                    type="datetime-local"
                    class="form-control"
                    name="expireTime"
                    id="expireTime"
                    required
                  />
                </div>
                <span class="help-block m-b-none"
                  ><i class="fa fa-info-circle"></i>
                  设备活跃窗口内未发送将过期</span
                >
              </div>
            </div>

            <!-- 动态表单字段容器 -->
            <div id="dynamicFormFields" class="mt-4">
              <div class="ibox float-e-margins">
                <div class="ibox-title">
                  <h5>配置参数</h5>
                </div>
                <div class="ibox-content">
                  <div class="alert alert-info">
                    请选择设备以自动加载配置参数
                  </div>
                </div>
              </div>
            </div>

            <!-- 隐藏的指令内容字段 -->
            <input
              type="hidden"
              name="commandContent"
              id="commandContent"
              required
            />

            <!-- 表单操作按钮 -->
            <!-- 不使用自定义按钮，使用模态框自带的确定/关闭按钮 -->
            <input type="hidden" name="submitType" value="confirm" />
          </form>
        </div>
      </div>
    </div>
    <th:block th:insert="~{include :: footer}" />
    <script th:inline="javascript">
      var prefix = ctx + "deviceManager/command";

      // 设置默认过期时间为当前时间加24小时
      var now = new Date();
      now.setHours(now.getHours() + 24);
      var defaultExpirationTime = now.toISOString().slice(0, 16);
      $("#expireTime").val(defaultExpirationTime);

      // 不展示字段列表
      var hiddenFields = ["rs485_id", "type", "properties.runcount"];

      // 保存设备列表数据
      var deviceListData = [];

      // 加载设备列表
      function loadDeviceList() {
        console.log("开始加载设备列表");
        console.log("请求URL: " + ctx + "deviceManager/device/activeList");
        $.ajax({
          url: ctx + "deviceManager/device/activeList",
          type: "GET",
          dataType: "json",
          success: function (result) {
            console.log("设备列表请求成功，返回结果:", result);
            if (result.code === 200 || result.code === 0) {
              // 保存设备列表数据
              deviceListData = result.data;

              var deviceSelect = $("#deviceId");
              deviceSelect
                .empty()
                .append('<option value="">请选择设备</option>');
              console.log("设备列表数据数量: ", result.data.length);

              $.each(result.data, function (index, device) {
                console.log(
                  "添加设备选项: ",
                  device.devName,
                  "ID:",
                  device.devId
                );
                var option = $(
                  '<option value="' +
                    device.devId +
                    '">' +
                    device.devName +
                    " (ID:" +
                    device.devId +
                    ")</option>"
                );
                deviceSelect.append(option);
              });
              // 添加后检查下拉框内容
              console.log(
                "下拉框选项数量: ",
                deviceSelect.find("option").length
              );
            } else {
              console.error("加载设备列表失败: " + result.msg);
              $.modal.alertError("加载设备列表失败：" + result.msg);
            }
          },
          error: function (xhr, status, error) {
            console.error("加载设备列表错误: ", status, error);
            console.error("XHR响应: ", xhr);
            $.modal.alertError("加载设备列表失败");
          },
        });
      }

      // 选择设备后自动从后台获取配置参数并生成表单
      $("#deviceId").change(function () {
        var deviceId = $(this).val();
        var deviceName = $(this).find("option:selected").text();

        if (deviceId && deviceName) {
          console.log("选择的设备ID: " + deviceId);
          console.log("选择的设备名称: " + deviceName);

          // 显示加载动画
          var formContainer = $("#dynamicFormFields");
          formContainer.html(
            '<div class="ibox float-e-margins"><div class="ibox-title"><h5>配置参数</h5></div><div class="ibox-content text-center"><img src="' +
              ctx +
              'img/loading.gif" /><p class="m-t">正在加载设备配置...</p></div></div>'
          );

          // 从保存的设备列表中查找当前选择的设备
          var selectedDevice = deviceListData.find(
            (device) => device.devId === parseInt(deviceId)
          );

          if (selectedDevice) {
            // 检查是否有attributes属性
            if (selectedDevice.attributes) {
              console.log("设备属性原始值: ", selectedDevice.attributes);

              // 确保attributes是对象类型，如果是字符串则尝试解析
              var attributesObj = selectedDevice.attributes;
              if (typeof attributesObj === "string") {
                try {
                  attributesObj = JSON.parse(attributesObj);
                  console.log("解析后的设备属性: ", attributesObj);
                } catch (e) {
                  console.error("解析设备属性失败: ", e);
                  // 解析失败时使用默认配置
                  $.modal.alertWarning("设备属性解析失败，使用默认配置");
                  var defaultJson = {
                    device_name: deviceName.replace(/\s*\(ID:\d+\)/, ""),
                    properties: {
                      time1: 0,
                      time2: 0,
                      time3: 0,
                      time4: 0,
                      time5: 0,
                      time6: 0,
                      time7: 0,
                      time8: 0,
                    },
                  };
                  generateFormFromJson(defaultJson);
                  return;
                }
              }

              // 使用设备的attributes直接生成表单
              generateFormFromJson(attributesObj);
            } else {
              console.log("设备没有attributes属性，使用默认配置");
              // 如果没有attributes属性，使用默认配置
              var defaultJson = {
                device_name: deviceName.replace(/\s*\(ID:\d+\)/, ""),
                properties: {
                  time1: 0,
                  time2: 0,
                  time3: 0,
                  time4: 0,
                  time5: 0,
                  time6: 0,
                  time7: 0,
                  time8: 0,
                },
              };
              generateFormFromJson(defaultJson);
            }
          } else {
            console.error("未找到选中的设备");
            $.modal.alertError("未找到选中的设备");
          }
        } else {
          // 清空表单区域
          var formContainer = $("#dynamicFormFields");
          formContainer.empty();

          // 创建提示信息
          var ibox = $("<div class='ibox float-e-margins'></div>");
          var iboxTitle = $("<div class='ibox-title'><h5>配置参数</h5></div>");
          var iboxContent = $("<div class='ibox-content'></div>");
          iboxContent.html(
            "<div class='alert alert-info'>请选择设备以自动加载配置参数</div>"
          );

          ibox.append(iboxTitle);
          ibox.append(iboxContent);
          formContainer.append(ibox);
        }
      });

      // 根据JSON数据生成表单
      function generateFormFromJson(jsonObj) {
        try {
          var formContainer = $("#dynamicFormFields");
          var flatJson = flattenJson(jsonObj);

          formContainer.empty();

          // 创建带样式的表单容器
          var ibox = $("<div class='ibox float-e-margins'></div>");
          var iboxTitle = $(
            "<div class='ibox-title'><h5>配置参数 <small>共 " +
              Object.keys(flatJson).length +
              " 个字段</small></h5></div>"
          );
          var iboxContent = $("<div class='ibox-content'></div>");

          // 创建一个表格来展示字段
          var table = $(
            "<table class='table table-striped table-hover table-responsive'></table>"
          );
          var thead = $(
            "<thead><tr class='bg-primary'><th>字段名</th><th>值</th><th>描述</th></tr></thead>"
          );
          var tbody = $("<tbody></tbody>");

          // 遍历扁平化的JSON对象，创建表单字段
          var fieldCount = 0;
          for (var key in flatJson) {
            if (flatJson.hasOwnProperty(key)) {
              // 检查是否在不展示列表中
              if (hiddenFields.includes(key)) {
                continue;
              }
              fieldCount++;

              var tr = $("<tr class='animated fadeIn'></tr>");
              tr.css("animationDelay", fieldCount * 50 + "ms");

              var keyTd = $(
                "<td class='font-bold'><strong>" + key + "</strong></td>"
              );
              var valueTd = $("<td></td>");
              var descTd = $("<td></td>");

              // 创建输入字段
              var input;

              // 为时间相关字段添加特殊处理，确保它们是可编辑的
              if (key.includes("time")) {
                input = $(
                  "<input type='text' class='form-control dynamic-field time-field' data-field='" +
                    key +
                    "' value='" +
                    flatJson[key] +
                    "' placeholder='请输入" +
                    getFieldDescription(key) +
                    "' style='background-color: #fff;'>"
                );
                input.prop("readonly", false); // 确保时间字段是可编辑的
              } else if (typeof flatJson[key] === "number") {
                input = $(
                  "<input type='text' class='form-control dynamic-field is-number' data-field='" +
                    key +
                    "' value='" +
                    flatJson[key] +
                    "' placeholder='请输入" +
                    getFieldDescription(key) +
                    "'>"
                );
              } else if (typeof flatJson[key] === "boolean") {
                // 布尔值使用下拉选择
                var select = $(
                  "<select class='form-control dynamic-field' data-field='" +
                    key +
                    "'></select>"
                );
                select.append(
                  "<option value='true'" +
                    (flatJson[key] === true ? " selected" : "") +
                    ">true</option>"
                );
                select.append(
                  "<option value='false'" +
                    (flatJson[key] === false ? " selected" : "") +
                    ">false</option>"
                );
                valueTd.append(select);
              } else {
                input = $(
                  "<input type='text' class='form-control dynamic-field' data-field='" +
                    key +
                    "' value='" +
                    flatJson[key] +
                    "' placeholder='请输入" +
                    getFieldDescription(key) +
                    "'>"
                );
              }

              // 如果创建了输入框，添加到单元格中
              if (input) {
                valueTd.append(input);
              }

              // 添加描述信息
              var desc = getFieldDescription(key);
              if (desc) {
                descTd.append(
                  "<small class='text-muted'><i class='fa fa-info-circle'></i> " +
                    desc +
                    "</small>"
                );
              }

              tr.append(keyTd);
              tr.append(valueTd);
              tr.append(descTd);
              tbody.append(tr);
            }
          }

          table.append(thead);
          table.append(tbody);
          iboxContent.append(table);

          // 如果没有生成任何字段
          if (tbody.find("tr").length === 0) {
            iboxContent.html(
              "<div class='alert alert-warning text-center'><i class='fa fa-exclamation-circle'></i> 没有可展示的字段</div>"
            );
          }

          ibox.append(iboxTitle);
          ibox.append(iboxContent);
          formContainer.append(ibox);

          // 为数字输入框添加样式
          $(".is-number").addClass("text-right");
        } catch (e) {
          $.modal.alertError("配置解析错误：" + e.message);
        }
      }

      // 将嵌套的JSON对象扁平化为键值对
      function flattenJson(obj, prefix = "", result = {}) {
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            const newKey = prefix ? `${prefix}.${key}` : key;
            if (
              obj[key] &&
              typeof obj[key] === "object" &&
              !Array.isArray(obj[key])
            ) {
              flattenJson(obj[key], newKey, result);
            } else {
              result[newKey] = obj[key];
            }
          }
        }
        return result;
      }

      // 获取字段描述信息
      function getFieldDescription(fieldName) {
        let descriptions = {
          device_name: "设备名称",
          device_id: "设备ID",
          BAT_V: "电池电压(mV)",
          "properties.time1": "参数1",
          "properties.time2": "参数2",
          "properties.time3": "参数3",
          "properties.time4": "参数4",
          "properties.time5": "参数5",
          "properties.time6": "参数6",
          "properties.time7": "参数7",
          "properties.time8": "参数8",
          "properties.X1": "参数X1",
          "properties.Y1": "参数Y1",
          "properties.Heart_T": "心跳间隔(秒)",
          "properties.ALARM": "报警状态",
        };
        return descriptions[fieldName] || "";
      }

      // 提交处理函数
      function submitHandler() {
        try {
          // 检查是否已生成表单
          let dynamicFields = $("#dynamicFormFields").find(".dynamic-field");
          if (dynamicFields.length === 0) {
            $.modal.alertWarning("请先选择设备以加载配置参数");
            return;
          }

          // 构建嵌套的JSON对象
          let nestedJson = {};
          dynamicFields.each(function () {
            let fieldPath = $(this).data("field");
            let value = $(this).val();

            // 解析字段路径，重建嵌套结构
            let pathParts = fieldPath.split(".");
            let current = nestedJson;

            for (let i = 0; i < pathParts.length; i++) {
              let part = pathParts[i];
              if (i === pathParts.length - 1) {
                // 如果是最后一部分，设置值
                // 尝试转换为数字
                if (!isNaN(value) && value !== "") {
                  current[part] = Number(value);
                } else {
                  current[part] = value;
                }
              } else {
                // 否则创建对象
                if (!current[part]) {
                  current[part] = {};
                }
                current = current[part];
              }
            }
          });

          // 确保包含设备ID和指令类型
          let deviceId = $("#deviceId").val();
          let commandType = $("#commandType").val();

          if (commandType === "CONFIG_UPDATE" && !nestedJson.properties) {
            // 对于CONFIG_UPDATE类型，确保有properties节点
            nestedJson.properties = {};
          }

          // 将构建好的JSON对象转换为字符串
          let commandContent = JSON.stringify(nestedJson);
          $("#commandContent").val(commandContent);

          // 提交表单
          $.operate.save(prefix + "/add", $("#form-command-add").serialize());
        } catch (e) {
          $.modal.alertError("表单处理错误：" + e.message);
        }
      }

      // 页面加载完成后加载设备列表
      $(document).ready(function () {
        loadDeviceList();
        
        // 绑定模态框的确认按钮事件
        window.parent.$('#layui-layer' + window.name.split('_')[1]).find('.layui-layer-btn0').click(function(){
          submitHandler();
        });
      });
    </script>
  </body>
</html>
